package com.mdinfo.system.web;

import com.mdinfo.system.service.IDemoService;
import org.springframework.http.HttpRequest;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.async.DeferredResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by Administrator on 2018/1/4.
 */
@RestController
@RequestMapping("/test")
public class Demo {

    @Resource
    private IDemoService demoService;

    @RequestMapping("/a")
    public String test(Integer a){
        if(a==1){
            try {
                Thread.sleep(100000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "a";
    }

    public String topic(HttpServletRequest request, HttpServletResponse response){
        request.getParameter("a");

        try {
            response.getWriter().write("abc");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "abc";
    }

    @GetMapping("/test02")
    public DeferredResult<String> test02(){

        DeferredResult<String> result =
                new DeferredResult<>(3000L,"timeout2");
        ListenableFuture<String> future = demoService.test02();

        result.onTimeout(()->{
            future.cancel(true);
        });

        System.out.println("controller线程:"+Thread.currentThread().getName());
        future.addCallback(new ListenableFutureCallback<String>() {
            @Override
            public void onFailure(Throwable ex) {
                ex.printStackTrace();
                System.out.println("onFailure");
                result.setResult("fail");
            }

            @Override
            public void onSuccess(String resp) {
                System.out.println("onSuccess");
                result.setResult(resp);
            }
        });
        return result;
    }
}
